package com.javajun.endofterm.controller.api_v1;

import com.javajun.endofterm.common.AjaxUtils;
import com.javajun.endofterm.common.DataGridParam;
import com.javajun.endofterm.common.DataGridUtils;
import com.javajun.endofterm.entity.Domitory;
import com.javajun.endofterm.entity.ExpressDelivery;
import com.javajun.endofterm.service.DomitoryService;
import com.javajun.endofterm.service.ExpressDeliveryService;
import com.javajun.endofterm.service.StudentService;
import com.javajun.endofterm.web.form.ExpressDeliveryForm;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Date;
import java.util.HashSet;

/**
 * Created with IntelliJ IDEA.
 * Description: 快递管理API
 * Author: Xiong Limin
 * Date: 2020-12-03-11:26 下午
 */
@RequestMapping("/api-v1/expressDelivery")
@RestController
public class ExpressDeliveryController{
    @Autowired
    private ExpressDeliveryService expressDeliveryService;

    @Autowired
    private DomitoryService domitoryService;

    @Autowired
    private StudentService studentService;

    @RequestMapping(value = "/page")
    public Object page(DataGridParam param) {
        if (param.getLimit() == null) {
            param.setLimit(15);
        }
        if (param.getPage() == null) {
            param.setPage(1);
        }

        Sort sort = Sort.by(Sort.Direction.DESC, "inputTime"); // 默认按照录入时间逆序排列
        Pageable pageable = param.getPageable(sort);
        Page<ExpressDelivery> page = expressDeliveryService.findAll(pageable);
        /**
         * 学生用户登录,只返回当前用户所在的宿舍的快递信息
         */
        boolean flag = studentService.whetherStudent();
        if (flag) {
            int domitoryId = studentService.getLodStudentDomitoryId();
            Page<ExpressDelivery> exp = expressDeliveryService.findByDomitoryId(pageable, domitoryId);
            return DataGridUtils.buildResult(exp);
        }

        return DataGridUtils.buildResult(page);
    }

    @RequestMapping(value = "/search")
    public Object search(DataGridParam param, ExpressDeliveryForm form) {
        Sort sort = Sort.by(Sort.Direction.DESC, "inputTime"); // 默认按照录入时间逆序排列
        Pageable pageable = param.getPageable(sort);
        System.out.println("domi: " + form.getDomiId());
        Specification<ExpressDelivery> spec = buildSpec(form);
        Page<ExpressDelivery> page = expressDeliveryService.findAll(spec, pageable);
        return DataGridUtils.buildResult(page);
    }

    /**
     * 动态安全查询
     * @param form
     * @return Specifitation<ExpressDelivery>
     */
    public Specification<ExpressDelivery> buildSpec(ExpressDeliveryForm form) {
        Specification<ExpressDelivery> spec = new Specification<ExpressDelivery>() {

            private static final long serialVersionUID = -1545840145475413952L;

            @Override
            public Predicate toPredicate(Root<ExpressDelivery> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                HashSet<Predicate> rules=new HashSet<>();
                if (StringUtils.hasText(form.getKeyword())) {
                    String keyword = form.getKeyword();
                    Predicate p1 = cb.like(root.get("orderNumber"), "%"+keyword+"%");
                    Predicate p2 = cb.like(root.get("domitory").get("name"), "%"+keyword+"%");
                    Predicate p3 = cb.like(root.get("addressee"), "%"+keyword+"%");
                    Predicate p4 = cb.like(root.get("pickUpName"), "%"+keyword+"%");
                    Predicate p5 = cb.like(root.get("pickUpCode"), "%"+keyword+"%");
                    Predicate or = cb.or(p1, p2, p3, p4, p5);
                    rules.add(or);
                }

                System.out.println("whetherStudent: " + studentService.whetherStudent());
                /*如果当前登录用是学生用户,则只查询该学生所在宿舍*/
                if (studentService.whetherStudent()) {
                    Integer domiId = studentService.getLodStudentDomitoryId();
                    if (domiId != null) {
                        Predicate id = cb.equal(root.get("domitory").get("id"), domiId);
                        rules.add(id);
                    }
                }

                return cb.and(rules.toArray(new Predicate[rules.size()]));
            }
        };
        return  spec;
    }

    @RequestMapping("/add")
    private Object addExpressDelivery(@RequestBody ExpressDeliveryForm form) {
        Integer domitoryId = form.getDomitoryId();
        Domitory domitory = domitoryService.findById(domitoryId);
        ExpressDelivery expressDelivery = new ExpressDelivery();
        BeanUtils.copyProperties(form, expressDelivery);
        expressDelivery.setDomitory(domitory);
        expressDelivery.setWhetherPickUp(0);
        expressDeliveryService.save(expressDelivery);
        return AjaxUtils.buildResult("快递添加成功");
    }

    @RequestMapping("/delete")
    public Object deleteExpressDlivery(Integer id) {
        expressDeliveryService.deleteById(id);
        return AjaxUtils.buildResult("删除快递成功");
    }

    @RequestMapping(value = "/pickup")
    public Object pickupExpress(Integer id, String name) {
        ExpressDelivery delivery = expressDeliveryService.findById(id);
        delivery.setPickUpName(name);
        delivery.setWhetherPickUp(1);
        delivery.setPickUpTime(new Date());
        expressDeliveryService.save(delivery);
        return AjaxUtils.buildResult("取件成功");
    }
}
